# -*- coding:utf-8 -*-
import json
import time
from datetime import datetime


# 日志输出
class MyLog:
    __LOG_PATH__ = "log/"

    def __init__(self, filename):
        self.object = open(self.__LOG_PATH__ + filename, "w")

    def write(self, str):
        self.object.write("[%s]....%s\n" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), str))
        self.object.flush()


# json解析
class MyJson:
    __JSON_PATH__ = "cache/"

    def __init__(self, filename=None, dict=None):
        if filename:
            fp = file(self.__JSON_PATH__ + filename, "r")
            self.object = json.load(fp, encoding='utf-8')
            fp.close()
        elif dict:
            self.object = dict

    # 获得当前命令
    def get_cmd(self):
        return self.object['command']

    # 获得目标地址
    def get_address(self):
        return self.object['host'], int(self.object['port'])

    # 获得客户端文件
    def get_client_file(self):
        return self.object['client_file']

    # 获得目标文件地址
    def get_server_file(self):
        return self.object['server_file']

    def save(self, filename):
        fp = file(self.__JSON_PATH__ + filename, "w")
        json.dump(self.object, fp)
        fp.close()


def my_size(size, index=0):
    DI = ["B", "KB", "MB", "GB"]
    if size < 1000:
        return str(size) + DI[index]
    else:
        return my_size(float(size / 1000), index + 1)


# 每秒输出时间 伪多线程
class MyTimer:
    def __init__(self, differ=1):
        self.start = 0
        self.differ = differ
        self.filesize = 0

    def get(self, filesize, total):
        if self.start == 0:
            self.start = datetime.now()
            self.filesize = filesize
            return None
        elif (datetime.now() - self.start).seconds >= self.differ:
            self.start = datetime.now()
            speed = my_size(filesize - self.filesize) + "/" + str(self.differ) + "s"
            try:
                process = str('%.2f%%' % (float(filesize) / float(total) * 100))
            except ZeroDivisionError:
                process = "0%"
            self.filesize = filesize
            return speed + '\t' + process


if __name__ == "__main__":
    pass
